package com.sq.universe.base.service.impl;

import com.sq.universe.base.dao.AuthorityDao;
import com.sq.universe.base.entity.AuthorityEntity;
import com.sq.universe.base.service.AuthorityService;
import com.sq.universe.system.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.chrono.IsoEra;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class AuthorityServiceImpl extends BaseServiceImpl<AuthorityEntity, AuthorityDao> implements AuthorityService {

    @Autowired
    private AuthorityDao authorityDao;

    @Override
    public UserEntity getUser(UserEntity userEntity) {
        return authorityDao.getUser(userEntity);
    }

    @Override
    public UserEntity getUserById(Integer userId) {
        return authorityDao.getUserById(userId);
    }

    @Override
    public RoleEntity getRoleById(Integer roleId) {
        return authorityDao.getRoleById(roleId);
    }

    @Override
    public RoleEntity getRoleByCode(String roleCode) {
        return authorityDao.getRoleByCode(roleCode);
    }

    @Override
    public MenuEntity getMenuByCode(String menuCode) {
        return authorityDao.getMenuByCode(menuCode);
    }

    @Override
    public List<UserRoleEntity> queryUserRole(UserRoleEntity userRoleEntity) {
        return authorityDao.queryUserRole(userRoleEntity);
    }

    @Override
    public List<RoleMenuEntity> queryRoleMenu(RoleMenuEntity roleMenuEntity) {
        return authorityDao.queryRoleMenu(roleMenuEntity);
    }

    @Override
    public List<Map> queryMenu(UserEntity userEntity){
        List<MenuEntity> list = authorityDao.queryMenu(userEntity);
        List<MenuEntity> tree =  buildTree(list);
        return new ArrayList<>();
    }

    public static List<MenuEntity> buildTree(List<MenuEntity> menuList) {
        List<MenuEntity> result = new ArrayList<>();
        for (MenuEntity menu : menuList) {
            if (menu.getMenuParentCode().equals("universe")) {
                result.add(menu);
                setChildren(menuList, menu);
            }
        }
        return result;
    }

    public static void setChildren(List<MenuEntity> list, MenuEntity parent) {
        for (MenuEntity menu : list) {
            if(parent.getMenuCode().equals(menu.getMenuParentCode())){
                parent.getChildren().add(menu);
            }
        }
        if (parent.getChildren().isEmpty()) {
            return;
        }
        for (MenuEntity menu: parent.getChildren()) {
            setChildren(list, menu);
        }
    }

    @Override
    public List<String> queryAuth(UserEntity userEntity) {
        return null;
    }

    public List<UserDepartmentEntity> queryUserDepartment(UserDepartmentEntity userDepartmentEntity){
        return authorityDao.queryUserDepartment(userDepartmentEntity);
    }
}
